import type { InjectionKey, SetupContext, UnwrapRef } from "vue";
import type { RuleItem, ValidateError } from "../utils/async-validator";
import type { Arrayable } from "../utils/types";
import type {
  FormProps,
  FormItemProps,
  FormLabelWidthContext,
  FormEmits,
} from "../config";
export interface FormItemRule extends RuleItem {
  trigger?: Arrayable<string>;
}
export type FormValidationResult = Promise<boolean>;
export type FormValidateCallback = (errors: ValidateError[]) => void;
export interface FormItemContext {
  props: Required<FormItemProps>;
  message: string;
  resetField(): void;
  clearValidate(): void;
  clickHandler(): void;
}
export type FormRules = Partial<Record<string, Arrayable<FormItemRule>>>;

export type FormContext = UnwrapRef<FormLabelWidthContext> & {
  props: Required<FormProps>;
  originalModel: Record<string, any>;
  emit: SetupContext<FormEmits>["emit"];
  // expose
  addField: (field: FormItemContext) => void;
  removeField: (field: FormItemContext) => void;
  resetFields: (props?: Arrayable<string>) => void;
  clearValidate: (props?: Arrayable<string>) => void;
  validateField: (
    props: Array<string>,
    callback: FormValidateCallback,
    event?: string
  ) => Promise<void>;
};

export const formContextKey: InjectionKey<FormContext> =
  Symbol("EFormContextKey");
export const formItemContextKey: InjectionKey<FormItemContext> = Symbol(
  "EFormItemContextKey"
);
